package com.superatom.concurrent.share;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 此类不是线程安全
 */
class Pair {
    private int x, y;
    public Pair(int x, int y){
        this.x = x;
        this.y = y;
    }

    public Pair(){
        this(0, 0);
    }

    public int getX() {
        return x;
    }

    // 自增不是原子性操作，不具有线程安全
    public void incrementX() {
        x++;
    }

    public int getY() {
        return y;
    }

    // 自增不是原子性操作，不具有线程安全
    public void incrementY() {
        y++;
    }

    @Override
    public String toString() {
        return "Pair{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }

    public class PairValuesNotEqualException extends RuntimeException {
        public PairValuesNotEqualException(){
            super("Pair values not equal: " + Pair.this);
        }
    }

    public void checkState(){
        if (x != y){
            throw new PairValuesNotEqualException();
        }
    }
}

abstract class PairManager{
    AtomicInteger checkCounter = new AtomicInteger(0);
    protected Pair p = new Pair();

    private List<Pair> storage = Collections.synchronizedList(new ArrayList<Pair>());

    // 对线程不安全的Pair，操作时要考虑同步问题
    public synchronized Pair getPair(){
        return new Pair(p.getX(), p.getY());
    }

    protected void store(Pair p){
        storage.add(p);
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public abstract void increment();
}

class PairManager1 extends PairManager{

    public synchronized void increment() {
        p.incrementX();
        p.incrementY();
        store(getPair());
    }
}

class PairManager2 extends PairManager{

    public synchronized void increment() {
        Pair temp;

        synchronized (this){
            p.incrementX();
            p.incrementY();
            temp = p;
        }
        // 由于该方法是把Pair对象放在synchronized ArrayList中，因此是线程安全的，可以放在synchronized语句块外面
        store(temp);
    }
}

/**
 * 调用PairManager子类做Pair对象递增工作
 */
class PairManipulator implements Runnable{
    private PairManager pm;

    public PairManipulator(PairManager pm){
        this.pm = pm;
    }

    public void run() {
        while (true){
            pm.increment();
        }
    }

    @Override
    public String toString() {
        return "Pari: " + pm.getPair() + "checkCounter = " + pm.checkCounter.get();
    }
}

/**
 * 调用PairManager子类做检查Pair对象的x，y值是否相同工作
 */
class PairChecker implements Runnable {
    private PairManager pm;

    public PairChecker(PairManager pm){
        this.pm = pm;
    }
    public void run() {
        while (true){
            pm.checkCounter.incrementAndGet();
            pm.getPair().checkState();
        }
    }
}

/**
 * 本Demo中，
 * PairManager1使用对整个方法进行同步的方式，
 * PairManager2使用同步控制块进行同步，
 * 为此，PairManager1加锁的时间比PairManager2要长，所以PairManager1.increment()的次数比PairManager2.increment()要少
 *
 * 这就表明了使用synchronized同步控制块的效率优势
 */
public class CriticalSection {
    static  void testApproaches(PairManager pman1, PairManager pman2){
        ExecutorService exec = Executors.newCachedThreadPool();
        // 对Pair递增操作
        PairManipulator pm1 = new PairManipulator(pman1);
        PairManipulator pm2 = new PairManipulator(pman2);

        // 对Pair检查工作
        PairChecker pcheck1 = new PairChecker(pman1);
        PairChecker pcheck2 = new PairChecker(pman2);

        exec.execute(pm1);
        exec.execute(pm2);
        exec.execute(pcheck1);
        exec.execute(pcheck2);


        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("pm1: " + pm1 + "\npm2: " + pm2);
        System.exit(0);
    }

    public static void main(String[] args) {
        PairManager pman1 = new PairManager1();
        PairManager pman2 = new PairManager2();

        testApproaches(pman1, pman2);
    }
}
